package datatft.springboot.web;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import com.alibaba.fastjson.JSON;
import me.zhyd.oauth.cache.AuthCacheConfig;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.log.Log;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthGoogleRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
public class HelloController {


    @GetMapping("/hello")
    public String sayHello() {
        return "Hello，Spring Boot！";
    }

    @GetMapping("/google/login")
    public String renderAuth(String state) {
        AuthRequest authRequest = getAuthRequest();

        return authRequest.authorize(state);
    }

    private static TimedCache<String, String> timedCache = CacheUtil.newTimedCache(10 * 60 * 1000);

    @GetMapping("/google/callback")
    public AuthUser login(AuthCallback callback, HttpServletRequest request) {
        String state = callback.getState();
        String code = callback.getCode();
        String key = state + "_" + code;
        String dataInCache = timedCache.get(key);
        if (StringUtils.isNotEmpty(dataInCache)) {
            Log.debug("return cache:"  + callback.getState() + "," + JSON.toJSONString(dataInCache));
            return JSON.parseObject(dataInCache, AuthUser.class);
        }
        
        long time = new Date().getTime();
        Log.debug("start:" + JSON.toJSONString(callback) + "," + request.getParameter("t"));
        AuthRequest authRequest = getAuthRequest();
        AuthResponse<AuthUser> login = authRequest.login(callback);
        Log.debug("end:" + callback.getState() + "," + JSON.toJSONString(login.getData()));
        Log.debug("end-time:" + (new Date().getTime() - time) / 1000);
        AuthUser data = login.getData();
        timedCache.put(state+ "_" + code , JSON.toJSONString(data));

        return data;
    }

    private static AuthRequest getAuthRequest() {
        AuthCacheConfig.timeout = 10 * 60 * 1000;
        return new AuthGoogleRequest(AuthConfig.builder()
                .clientId("543894697911-scot7qdmhqpu31q3fdl79hp9gcb1ipbn.apps.googleusercontent.com")
                .clientSecret("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")
                .redirectUri("https://api.datatft.com" + "/user/google/callback")
//                .redirectUri("http://localhost:8098" + "/user/google/callback")
                // 针对国外平台配置代理
                .build());
    }
}
